package com.tian.service.impl.management;


import com.tian.common.enums.ResultCode;
import com.tian.common.util.Result;
import com.tian.dto.management.req.RoleAddReqDto;
import com.tian.dto.management.resp.PageDto;
import com.tian.dto.management.resp.RoleRespDto;
import com.tian.entity.Role;
import com.tian.mapper.RoleMapper;
import com.tian.mapper.UserRoleMapper;
import com.tian.service.management.RoleService;
import com.tian.service.management.UserRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-09-10 8:32
 * {@code @version:} 1.0
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;

    @Override
    public Result<PageDto<List<RoleRespDto>>> allRole() {
        List<Role> roles = roleMapper.selectAll();
        List<RoleRespDto> roleRespDtoList = new ArrayList<>();
        for (Role role : roles) {
            RoleRespDto roleRespDto = new RoleRespDto();
            roleRespDto.setId(role.getId());
            roleRespDto.setRoleName(role.getRoleName());
            roleRespDtoList.add(roleRespDto);
        }
        PageDto<List<RoleRespDto>> pageDto = new PageDto<>();
        pageDto.setData(roleRespDtoList);
        pageDto.setTotalCount(roleRespDtoList.size());
        return Result.success(pageDto);
    }

    @Override
    public Result deleteRole(Integer id) {
        int count = userRoleMapper.countByRoleId(id);
        if (count > 0) {
            return Result.fail(ResultCode.ROLE_USED);
        }
        roleMapper.deleteByPrimaryKey(id);
        return Result.success();
    }

    @Override
    public Result addRole(RoleAddReqDto roleAddReqDto) {
        Role role = roleMapper.selectByRoleName(roleAddReqDto.getRoleName());
        if (role != null) {
            return Result.fail(ResultCode.ROLE_NAME_EXIST);
        }
        role = new Role();
        role.setRoleName(roleAddReqDto.getRoleName());
        roleMapper.insert(role);
        return Result.success();
    }
}
